﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.DoorSpendCommand;
using D.Medicalcare.Read.API.Application.Command.OutpatientConsumptionCommand;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.OutpatientConsumptionHandler
{
    public class GetOutpatientConsumptionHandler : IRequestHandler<GetOutpatientConsumptionCommand, APIPaging<OutpatientConsumption>>
    {

        private readonly IBaseRepository<OutpatientConsumption> baseRepository;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseRepository"></param>
        /// <param name="mapper"></param>
        public GetOutpatientConsumptionHandler(IBaseRepository<OutpatientConsumption> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 获取充值消费处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPaging<OutpatientConsumption>> Handle(GetOutpatientConsumptionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIPaging<OutpatientConsumption> result = new APIPaging<OutpatientConsumption>();
                result.Code = APIEnum.Mvc;
                result.Msg = "查询成功";
                var list = baseRepository.GetAll().ToList();
                if (request.CreateTime != null)
                {
                    var targetDate = request.CreateTime.Value.Date;
                    list = list.Where(x => x.CreateTime.HasValue && x.CreateTime.Value.Date == targetDate).ToList();
                }
                if (!string.IsNullOrEmpty(request.Name))
                {
                    list = list.Where(x => x.Name.Contains(request.Name)).ToList();
                }


                result.TotalCount = list.Count();
                result.PageCount = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
                result.Data = list.OrderByDescending(a => a.OutpatientConsumptionId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
